<script lang="ts" setup>
import { ref } from "vue"
import SseConnection from "@/utils/sseUtil"
const sseUtil = new SseConnection()

const messages = ref<string[]>([]) // 消息列表
const isConnected = ref(false) // 是否连接中

// 模拟用户输入参数
const userParams = ref({
  param: "导入条件1",
  param2: "导入条件2"
})

// 开始 SSE 请求
const startImport = () => {
  if (!userParams.value.param.trim()) {
    alert("请输入参数！")
    return
  }

  messages.value = [] // 清空消息

  sseUtil.connect({
    url: `/test-sse/long-task`,
    params: userParams.value,
    onMessage: (message) => {
      messages.value.push(message)
    },
    onOpen: () => {
      console.log("SSE 连接成功")
      isConnected.value = true
    },
    onError: () => {
      alert("连接发生错误或断开")
      isConnected.value = false
    },
    onComplete: () => {
      console.log("SSE 任务完成")
      isConnected.value = false
    }
  })
}

// 断开 SSE 请求
const disconnectSse = () => {
  sseUtil.disconnect()
  isConnected.value = false
}
</script>

<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>SSE 实时消息</h3>
      <!-- 输入框，用于用户输入参数 -->
      <input v-model="userParams.param" placeholder="请输入参数1" />
      <input v-model="userParams.param2" placeholder="请输入参数2" />
      <button @click="startImport" :disabled="isConnected">开始导入</button>
      <button @click="disconnectSse" :disabled="!isConnected">断开连接</button>

      <h3>导入进度</h3>
      <!-- 展示服务端返回的消息 -->
      <ul>
        <li v-for="(message, index) in messages" :key="index">{{ message }}</li>
      </ul>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.message {
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #f9f9f9;
}
</style>
